package com.csun.action;

import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.csun.base.BaseAction;
import com.csun.entity.PageBean;
import com.csun.entity.User;
import com.csun.service.UserService;
import com.csun.util.ResponseKit;

/**
 * @ClassName: UserAction.java
 * @Description:用户控制核心类
 * @author danjinsong danjingsong@dragonwake.cn
 * @date 2017年2月16日下午3:40:14
 */
@SuppressWarnings("serial")
@Controller
public class UserAction extends BaseAction{

	private User user;									  //用户-----登陆个体
	private String errorMsg;							  //错误信息--登录使用
	private PageBean pageBean;							  //分页助手--查询使用	
	private User s_user;								  //查询助手--查询使用
	
	private Integer roleId;								  //角色Id---保存使用		

	@Autowired
	private UserService userService;
	//=============从此处开始为业务逻辑方法 ======================//
	/**
	 * 用户登录方法
	 * @return
	 */
	public String login(){
		try{
			User u ;
			if((u = userService.login(user)) != null){
				getSession().setAttribute("currentUser", u);
				return new RoteAction().index();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		errorMsg = "用户名或密码错误";
		return "error";
	}
	/**
	 * ajax请求列表方法
	 * @return
	 */
	public String list(){
		JSONObject json = new JSONObject();							//返回的json
		if(s_user!=null) s_user.setUserId(0); 						//标示为页面查询逆序
		List<User> userList = userService.find(s_user, pageBean);	//查询得到的集合
		JsonConfig config = new JsonConfig();						//配置json数组转化规则
		config.setExcludes(new String[]{"password"});               //密码不可以转化
		config.setCycleDetectionStrategy(
				CycleDetectionStrategy.LENIENT); 					//解开json循环
		JSONArray list = JSONArray.fromObject(userList,config);		//集合转json数组
		Long total = userService.count(s_user);						//对象总数
		json.put("page", pageBean.getPage());						//当前页放入json
		json.put("total", total);				 					//总数放入json
		json.put("list", list);										//json数组放入json
		json.put("success", true);									//返回成功信号
		ResponseKit.write(getresponse(), json);                     //json写回返回结果集
		return null;
	}
	/**
	 * 保存用户
	 * @return
	 */
	public String save(){
		if(user != null){
			userService.save(user,roleId);					//权限一起保存
			ResponseKit.write(getresponse(), "success");	//添加成功
		}
		else{
			ResponseKit.write(getresponse(), "error");		//添加失败
		}
		return null;
	}
	/**
	 * 判断用户名时候存在
	 * @return
	 */
	public String isExit(){
//		String  dt      	= getRequset().getParameter("dt");	
		String  fieldId 	= getRequset().getParameter("fieldId");
		String  fieldValue  = getRequset().getParameter("fieldValue");
		Object[] validateReturn = new Object[3];
		if(!userService.isExit(fieldValue)){  //如果不存在
            validateReturn[0] = fieldId;  
            validateReturn[1] = true;  
            validateReturn[2] = "可以使用";  
        }else {  
            validateReturn[0] = fieldId;   
            validateReturn[1] = false;  
            validateReturn[2] = "在指定用户名已经存在";  
        }  
		//返回对应格式的json数组
		ResponseKit.write(getresponse(), JSONArray.fromObject(validateReturn));
		return null;
	}
	/**
	 * 通过Id获取实体
	 * @return
	 */
	public String get(){
		Integer userId = Integer.parseInt(getRequset().getParameter("userId"));	//获取Id
		JsonConfig config = new JsonConfig();								   	//设置json转化配置	
		config.setExcludes(new String[]{"password"});						   	//忽略密码	
		config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); 		//解开json循环
		JSONObject user = 
				JSONObject.fromObject(userService.get(userId),config);			//查询用户并转化json
		JSONObject json = new JSONObject();										
		json.put("success", true);												//成功标识符
		json.put("user", user);													//转载user
		ResponseKit.write(getresponse(), json);									//输出json
		return null;
	}
	/**
	 * 批量删除 
	 * @return
	 */
	public String delete(){
		userService.delete(getRequset().getParameter("ids"));					//通过id批量删除
		ResponseKit.write(getresponse(), "success");
		return null;
	}
	//=============从此处开始为中间调用方法 =========================//
	
	
		 
		
	//=============从此处开始为 Get Set方法=======================//
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public String getErrorMsg() {
		return errorMsg;
	}
	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}
	public PageBean getPageBean() {
		return pageBean;
	}
	public void setPageBean(PageBean pageBean) {
		this.pageBean = pageBean;
	}
	public User getS_user() {
		return s_user;
	}
	public void setS_user(User s_user) {
		this.s_user = s_user;
	}
	public Integer getRoleId() {
		return roleId;
	}
	public void setRoleId(Integer roleId) {
		this.roleId = roleId;
	}
}
